package jobs.job2;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;

public class MyServer {

    RandomStringGenerator randomStringGenerator = new RandomStringGenerator();
    private ServerSocket serverSocket;
    public MyServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
        startListen();//监听多个客户端
        run();
    }
    List<PrintStream> clients = new LinkedList<>();//客户端列表
    Queue<Message> msgs = new ArrayBlockingQueue<>(100);
    private void startListen() {
        new Thread() {
            @Override
            public void run() {
                while (true) {
                    try {
                        final Socket socket = serverSocket.accept();

                        final String name = randomStringGenerator.randomName();
                        PrintStream printStream = new PrintStream(socket.getOutputStream());
                        printStream.println(
                                new Message(null,
                                        name,
                                        -1));//分配名称
                        clients.add(printStream);//添加新客户端

                        msgs.offer(new Message(String.valueOf(clients.size()), name, -2));//广播加入消息 "加入聊天室"

                        new Thread(){
                            @Override
                            public void run() {
                                try {
                                    Scanner scanner = new Scanner(socket.getInputStream());
                                    String line = scanner.nextLine();
                                    msgs.add(new Message(line, name, 0));//将客户端发来的消息添加到队列
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }.start();//监听每个客户端的输入

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

// 将一个用户发来的消息发送给每个用户
    public void run() {
        while (true) {
            Message msg = msgs.poll();
            if (msg != null)
                for (PrintStream printStream : clients)
                    printStream.println(msg.toString());
        }
    }

    public static void main(String[] args) throws IOException {
        new MyServer(8888);
    }

}
